import { createSlice } from '@reduxjs/toolkit'
import { clearToken, getToken, setToken } from '@/utils/token'
import { getUserLoginAPI } from '@/api/user'
import { message } from 'antd'
const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: []
  },
  // 同步修改方法
  reducers: {
    // 修改token
    setUserToken (state, action) {
      state.token = action.payload
      setToken(state.token)
    },
    // 登出
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      clearToken()
    }
  }
})

// 解构出actionCreater
const { setUserToken, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步封装,获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await getUserLoginAPI(loginForm)
    if (res.code === 1) {
      dispatch(setUserToken(res.data))
      message.success('登录成功')
      return true
    } else {
      message.error(res.msg)
      return false
    }
  }
}

export { fetchLogin, clearUserInfo }

export default userReducer